import {
  AutoComplete,
  Button,
  Empty,
  Input,
  message,
  Space,
  Table,
} from 'antd';
import React, { ChangeEvent, useContext, useMemo, useState } from 'react';
import cls from 'classnames';
import { ResourcesContext } from '../hooks';
import { TypographyTitle } from '@/components/Typography';
import {
  PlusOutlined,
  ReloadOutlined,
  CaretDownOutlined,
  CaretRightOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { getResouColumns } from '../components/PageConfig';
import { IResColumnsOpt, IResouFirstStep } from '../type';
import { switchResourIsOpen, useResManageReq } from '../hooks/useResManageReq';
import { loopArray } from '@/utils';
import { ResoucerAddEditModal } from './ResoucerAddEditModal';
import { useRequest } from 'umi';
import { ConfirmModal } from './ConfirmModal';

export const ResouFirstStep: React.FC<IResouFirstStep> = () => {
  const { prefixCls, curRes } = useContext(ResourcesContext);
  const { rouTreeData, resourceFresh, resourceLoading } = useResManageReq();

  // 表格操作方法
  const onPosOptClick: IResColumnsOpt = {
    onEditAdd: (record) => {
      if (record && record?.id) {
        setCheckRows(record); //编辑
      } else {
        setCheckRows({ detaID: record }); //用于选中数据,新增时候初始化上级资源
      }
      openShowAddEdit();
    },
    onChangeIsOpen: (checked, record) => {
      if (checked) {
        if (record?.pIsOpen == 1) {
          checkFalseIsOpen?.run(checked, record);
        } else if (record?.pIsOpen == 0) {
          openConfimModal(true);
        } else {
          checkFalseIsOpen?.run(checked, record);
        }
      } else {
        openConfimModal(true);
      }
    },
  };

  const [seachValue, setSeachValue] = useState<string>(''); //保存右侧树搜索的值
  // const [autoOption, setAutoOption] = useState<any[]>([]); //保存 AutoComplete 的下拉菜单值

  const [expandedKeys, setExpandedKeys] = useState<string[]>([]); //保存选中行的 父级行 key
  const [openSearchKey, setOpenSearchKey] = useState<any>([]); //保存选中项 的key
  const [checkRows, setCheckRows] = useState<any>(); //保存选中行的 row

  const [isShowAddEdit, setIsShowAddEdit] = useState<boolean>(false); //是否打开新增编辑modal
  const openShowAddEdit = () => {
    setIsShowAddEdit(true);
  };
  const closeShowAddEdit = () => {
    setIsShowAddEdit(false);
  };

  const [showConfimModal, setShowConfimModal] = useState<boolean>(false); //是否打开提示modal
  const openConfimModal = (openClose: boolean) => {
    setShowConfimModal(openClose);
  };

  // 修改下拉展开图标
  const expandIcon = (props: any) => {
    if (props.record.children && props.record.children.length > 0) {
      if (props.expanded) {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretDownOutlined />
            </span>
          </span>
        );
      } else {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretRightOutlined />
            </span>
          </span>
        );
      }
    } else {
      return (
        <span
          style={{
            float: 'left',
            marginRight: '5px',
          }}
        >
          <span style={{ fontSize: '10px', visibility: 'hidden' }}>
            <CaretRightOutlined />
          </span>
        </span>
      );
    }
  };

  /**
   * 搜索框改变
   * @param e
   */
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSeachValue(e.target.value);
  };

  /** 搜索框数据 */
  const autoOption = useMemo(() => {
    const tileArray: Record<string, any>[] =
      rouTreeData?.length > 0 ? loopArray(rouTreeData) : [];
    const newOption: any[] = tileArray
      ?.map((item) => {
        if ((item?.name ?? item?.text)?.includes(seachValue)) {
          // const name = item?.name ?? item?.text;
          // const nameLength = name?.length;
          // const select = name?.search(searchValue);
          // const searchLength = searchValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = searchValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          return {
            value: item?.name ?? item?.text,
            key: item?.id,
            // label: (
            //   <>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </>
            // ),
          };
        }
      })
      ?.filter((item) => typeof item !== 'undefined');
    return newOption;
  }, [seachValue, rouTreeData]);

  // 点击搜索框
  const onAutoSelect = (value: string, option: any) => {
    setSeachValue(value);
    const optionId = option?.key;
    const targetNode = loopArray(rouTreeData)?.find((i) => i?.id === optionId);
    setExpandedKeys([targetNode?.pID]);
    setOpenSearchKey([optionId]);
    setCheckRows(targetNode);

    // 滚动定位
    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);
  };

  /** 表格配置 */
  const columnsItems = useMemo(() => {
    return getResouColumns(curRes, onPosOptClick, seachValue);
  }, [curRes, seachValue]);

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  // 点击展开行
  const onExpandedRowsChange = (expands: any) => {
    if (expands) {
      setExpandedKeys(expands);
    }
  };

  // 表格选中项变化
  const tableChange = (selectedRowKeys: any, selectedRows: any) => {
    if (typeof selectedRowKeys == 'string') {
      let newSelectKeys = [selectedRowKeys];
      setOpenSearchKey(newSelectKeys);
      setCheckRows(selectedRows);
    } else {
      setOpenSearchKey(selectedRowKeys);
      setCheckRows(selectedRows[0]);
    }
  };

  // 刷新列表页面
  const tableReload = () => {
    resourceFresh();
  };

  // 调用修改状态的按钮
  const checkFalseIsOpen = useRequest(
    (openState: boolean, recObj: any) => {
      let params = {
        versionNum: recObj?.versionNum,
        id: recObj?.id,
        isOpen: openState ? 1 : 0,
      };
      return switchResourIsOpen(params);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          tableReload();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  // 禁用资源
  const chanageSwitch = (check: boolean, resObj: any) => {
    checkFalseIsOpen?.run(check, resObj);
  };

  return (
    <>
      <div className={cls(prefixCls + 'bottomCol')}>
        <div className={cls(prefixCls + 'divBox')}>
          <div className={cls(prefixCls + 'table-header')}>
            <TypographyTitle
              level={4}
              style={{
                margin: 0,
              }}
            >
              资源菜单
            </TypographyTitle>

            <Space>
              <AutoComplete
                options={autoOption}
                onSelect={onAutoSelect}
                notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                style={{ width: 400 }}
              >
                <Input
                  placeholder={'请按名称搜索'}
                  suffix={<SearchOutlined />}
                  onChange={onInputChange}
                  addonAfter={
                    <span
                      onClick={() => {
                        setSeachValue('');
                        resourceFresh();
                      }}
                    >
                      <ReloadOutlined />
                    </span>
                  }
                  allowClear
                />
              </AutoComplete>

              {!!curRes['/resourceController/add'] && (
                <Button
                  type={'primary'}
                  icon={<PlusOutlined />}
                  onClick={() => {
                    onPosOptClick?.onEditAdd(checkRows?.id);
                  }}
                >
                  添加
                </Button>
              )}

              {/* <Button
                icon={<ReloadOutlined />}
                onClick={() => {
                  resourceFresh();
                }}
              >
                重置
              </Button> */}
            </Space>
          </div>

          <div className={cls(prefixCls + 'table-content')}>
            <div className={cls('list-table')}>
              <Table
                size="small"
                columns={columnsItems}
                bordered
                pagination={false}
                dataSource={rouTreeData}
                loading={resourceLoading}
                rowKey={(record) => record?.id}
                expandIcon={expandIcon}
                scroll={{ x: 1200, y: 'true' }}
                // scroll={{ y: '100%' }}
                rowSelection={{
                  type: 'radio',
                  selectedRowKeys: openSearchKey,
                  onChange: tableChange,
                }}
                expandedRowKeys={expandedKeys}
                onExpandedRowsChange={onExpandedRowsChange}
                onRow={(record) => {
                  return {
                    onClick: (event) => {
                      event.stopPropagation();
                      tableChange(record?.id, record);
                    },
                  };
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {isShowAddEdit && (
        <ResoucerAddEditModal
          onClose={closeShowAddEdit}
          editAddRows={checkRows}
          visible={isShowAddEdit}
          rouTreeData={rouTreeData}
          tableReload={tableReload}
        />
      )}

      {showConfimModal && (
        <ConfirmModal
          onClose={() => {
            openConfimModal(false);
          }}
          visible={showConfimModal}
          onReload={tableReload}
          tableRowObj={checkRows}
          chanageSwitch={chanageSwitch}
        />
      )}
    </>
  );
};
